<template>
  <div class="employees">
    <div class="app-container">
      <el-card
        shadow="always"
        :body-style="{ padding: '20px' }"
      >
        <div slot="header">
          <page-tools>
            <!-- 插入到left插槽位置 -->
            <template #left>
              <span>总计100条数据</span>
            </template>
            <!-- 插入到right插槽位置 -->
            <template #right>
              <el-button
                type="warning"
                size="small"
                @click="$router.push('/import')"
              >导入excel</el-button>
              <el-button
                type="danger"
                size="small"
                :loading="downloadLoading"
                @click="exportData()"
              >导出excel</el-button>
              <el-button
                type="primary"
                size="small"
                @click="showDialog=true"
              >新增员工</el-button>
            </template>
          </page-tools>
        </div>
        <!-- table列表 -->
        <div>
          <el-table
            border
            :data="list"
            :default-sort="{prop: 'workNumber', order: 'descending'}"
          >
            <el-table-column
              label="序号"
              type="index"
            />
            <el-table-column
              label="姓名"
              prop="username"
            />
            <el-table-column label="头像">
              <template #default="{row}">
                <el-image
                  :src="row.staffPhoto"
                  fit="cover"
                  class="photo"
                  @click="openCode(row.staffPhoto)"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="工号"
              prop="workNumber"
            />
            <el-table-column label="聘用形式">
              <template #default="{row}">
                {{ formatFormOfEmployment(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column
              label="部门"
              prop="departmentName"
            />
            <el-table-column
              label="入职时间"
              sortable
              prop="correctionTime"
            />
            <el-table-column label="账户状态">
              <el-switch v-model="qy" />
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              width="280"
            >
              <template #default="{row}">
                <el-button
                  type="text"
                  size="small"
                  @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button>
                <el-button
                  type="text"
                  size="small"
                >分配角色</el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="delList(row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <el-pagination
              layout="prev, pager, next, sizes"
              :total="total"
              :current-page="params.page"
              :page-size="params.size"
              :page-sizes="[10,2]"
              @current-change="changePage"
              @size-change="sizeChange"
            />
          </el-row>
        </div>
      </el-card>
    </div>
    <!-- 新增员工弹层 -->
    <!--
      父传子.sync作用：可以同步修改绑定的变量值
      .sync语法糖：
        1、父传子 => :props.sync
        2、子传父 => 子组件中事件名 => update:props
     -->
    <AddEmploy :show-dialog.sync="showDialog" />
    <!-- 员工二维码 -->
    <QrCode
      ref="qr"
      :show-code.sync="showCode"
    />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees.js'
import diction from '@/api/constant/employees.js'
import AddEmploy from './components/add-employee.vue'
import QrCode from './components/qr-code.vue'
export default {
  components: {
    AddEmploy,
    QrCode
  },
  data () {
    return {
      showCode: false,
      downloadLoading: false,
      qy: true,
      // 员工列表
      list: [],
      params: {
        page: 1, // 当前页
        size: 10 // 每页多少条数据
      },
      total: 0, // 员工总条数
      showDialog: false
    }
  },
  created () {
    this.getList()
  },
  methods: {
    openCode (url) {
      this.showCode = true
      // 调用子组件draw方法绘制二维码
      this.$refs.qr.draw(url)
    },
    // 获取数据
    async getList () {
      const { rows, total } = await getEmployeeList(this.params)
      console.log(await getEmployeeList(this.params))
      this.list = rows
      this.total = total
    },
    // 页码切换

    changePage (page) {
      // 1、更新页码
      // 2、刷新列表数据
      this.params.page = page
      this.getList()
    },
    // 切换每页多少条数据
    sizeChange (size) {
      // 1、更新每页数据
      // 2、刷新列表数据
      this.params.size = size
      this.getList()
    },
    // 根据数据字典查询对应数字代表的含义（码值）
    formatFormOfEmployment (type) {
      /**
       * 思路：
       * 1、生成map映射关系
       * 2、根据map获取对应码值
       */
      const map = {}
      diction.hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[type]
    },
    // 删除用户
    async delList (row) {
      try {
        await this.$confirm(`你确定要删除${row.username}吗`, '温馨提示')
        await delEmployee(row.id)
        const newPage = Math.ceil((this.total - 1) / this.size)
        if (this.params.page > newPage) {
          this.params.page = newPage
        }
        this.getList()
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    async exportData () {
      this.downloadLoading = true
      // 异步导入模块：import('模块的路径') => 返回Promise对象
      const excel = await import('@/utils/Export2Excel')
      // 准备导出的excel表头和数据
      // const tHeader = ['姓名', '性别', '工资']
      // const data = []
      const { tHeader, secondArray } = this.provideData()
      excel.export_json_to_excel({
        // 导出数据的表头（数组）
        header: tHeader,
        // 导出的具体数据（二维数组）
        data: secondArray,
        // 导出文件名
        filename: `第${this.params.page}页员工数据`,
        // 单元格是否要自适应宽度
        autoWidth: true,
        // 导出文件类型
        bookType: 'xlsx'
      })
      this.downloadLoading = false
    },
    // 提供excel表头和数据的方法
    provideData () {
      // 指定导出员工数据的映射关系
      const header = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      // 表头
      const tHeader = Object.keys(header)
      // 指定导出的属性名
      const filterKeys = Object.values(header)
      /**
       * 1、准备一个空数组
       * 2、循环员工列表list，把指存到二维数组中
       * 3、返回处理完的二维数组
      */
      const secondArray = []
      this.list.forEach(item => {
        const userInfo = []
        for (const key in item) {
          if (filterKeys.includes(key)) {
            if (key === 'formOfEmployment') {
              userInfo.push(this.formatFormOfEmployment(item[key]))
            } else {
              userInfo.push(item[key])
            }
          }
        }
        secondArray.push(userInfo)
      })
      return { tHeader, secondArray }
    }
  }
}
</script>

<style lang="scss" scoped>
.photo {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
